#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2020-01-08 11:32:09
# @Author  : Lewis Tian (taseikyo@gmail.com)
# @Link    : github.com/taseikyo
# @Version : python3.8

"""
download & convert bilibili cc subtitles
to srt subtitle format
"""

import re
import sys

import requests


def obtain_cc_subtitle(avid="77948393"):
    """obtain cc subtitles
    @avid: id of the video
    """
    url = f"https://www.bilibili.com/video/av{avid}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
    }
    r = requests.get(url, headers=headers)
    subtitle_urls = re.findall(r"subtitle_url\":\"(.*?json)", r.text)
    if not subtitle_urls:
        print("There is no cc subtitle in this video!")
        return

    for url in subtitle_urls:
        url = url.replace("\\u002F", "/")
        r = requests.get(url, headers=headers)
        convert_to_srt(url.split("/")[-1].split(".")[0], r.json()["body"])


def convert_to_srt(srt_id, subtitles):
    """convert cc subtitles to srt subtitles
    @subtitles: a json foramt cc subtitles 00:00:52,430
    """
    srt = []
    for index, subtitle in enumerate(subtitles):
        fs, fms = divmod(subtitle["from"] * 1000, 1000)
        fm, fs = divmod(fs, 60)
        fh, fm = divmod(fm, 60)
        start = "{}:{}:{},{}".format(str(int(fh)).zfill(2), str(int(fm)).zfill(2), str(int(fs)).zfill(2),
                                     str(int(fms)).zfill(3))
        es, ems = divmod(subtitle["to"] * 1000, 1000)
        em, es = divmod(es, 60)
        eh, em = divmod(em, 60)
        end = "{}:{}:{},{}".format(str(int(eh)).zfill(2), str(int(em)).zfill(2), str(int(es)).zfill(2),
                                     str(int(ems)).zfill(3))
        srt_tmp = f"""{index+1}\n{start} --> {end}\n{subtitle["content"]}\n"""
        srt.append(srt_tmp)

    with open(f"/Users/xinyu.jiang/Desktop/tmp/{srt_id}.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt))


if __name__ == "__main__":
    arg1 = sys.argv[1]
    obtain_cc_subtitle(arg1)